package com.youlu.campus.service.file.impl;

import com.youlu.campus.base.exception.BusinessException;

import com.youlu.campus.component.QiniuConfig;
import com.youlu.campus.component.QiniuUtil;
import com.youlu.campus.service.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private QiniuConfig qiniuConfig;
    @Autowired
    private QiniuUtil qiniuUtil;

    @Override
    public String uploadFile(InputStream inputStream, String fileName) {
        log.info(":>>> 上传文件开始。。。 {}", fileName);
        String url = qiniuConfig.getDomainOfBucket();
        fileName = "excel" + System.currentTimeMillis() + fileName;
        try {
            //上传到七牛
            qiniuUtil.uploadFile(inputStream, fileName);
            url = url + "/" + fileName;
        } catch (IOException e) {
            log.error("<<<<<<<<<<<上传文件失败:{}", e);
            throw new BusinessException("文件上传失败！");
        }
        log.info(":>>> 结束 {}", url);
        return url;
    }

    @Override
    public String uploadFile(MultipartFile file) {
        log.info("上传图片开始。。。 {}", file.getOriginalFilename());
        String url = qiniuConfig.getDomainOfBucket();
        String fileName = "img" + System.currentTimeMillis() + file.getOriginalFilename();

        try {
            //上传到七牛
            qiniuUtil.uploadFile(file.getInputStream(), fileName);
            url = url + "/" + fileName;

        } catch (IOException e) {
            log.error("<<<<<<<<<<<上传文件失败", e);
            e.printStackTrace();
            throw new BusinessException("文件上传失败！");
        }

        log.info("上传图片结束 {}", url);

        return url;
    }
}
